from five import grok
from interfaces import IShortUrl, IShortUrlAdapter, IUrlSettingsUtility, IAddedShortUrlEvent
from Products.Archetypes.event import ObjectInitializedEvent
from Products.CMFCore.interfaces import IContentish
from zope.app.container.contained import ObjectAddedEvent, ObjectRemovedEvent, ObjectMovedEvent
from zope.app.container.interfaces import IObjectAddedEvent, IObjectMovedEvent
from zope.component import getAdapter, getUtility, queryUtility
from zope.interface import Interface, implements, alsoProvides, providedBy, noLongerProvides
from zope.lifecycleevent import ObjectModifiedEvent, ObjectEvent

class AddedShortUrlEvent(ObjectEvent):
    """
    This event is triggered when a new Short Url was adapted.
    Example code:
    @grok.subscribe(IShortUrl, AddedShortUrlEvent)
    def newShortUrlEventAdded(context, event):
        adapter = getAdapter(context, IShortUrlAdapter, name="short-url-adapter")
        utility = getUtility(IUrlSettingsUtility, name='url-settings')
        print "Short Url:", '/'.join(('http:/', utility.domain, adapter.shortCode))
    """
    grok.implements(IAddedShortUrlEvent)
    
    def __init__(self, context, REQUEST=None):
        """
        Initializing object.
        """
        self.object = context
        self.request = REQUEST

@grok.subscribe(IContentish, ObjectInitializedEvent)
def provideShortUrlMarkerInterface(context, event):
    """
    This event provides the IShortUrl interface for the current context
    if the portal type is found in the configuration of the control panel.
    """
    urlSettingsUtility = getUtility(IUrlSettingsUtility, name='url-settings')
    types = urlSettingsUtility.getContentTypes()
    if types.has_key(context.portal_type):
        alsoProvides(context, IShortUrl)
        context.reindexObject()

@grok.subscribe(IShortUrl, ObjectModifiedEvent)
def shortUrlChanged(context, event):
    """
    This subscriber mainly updates the indexes if the remoteUrl has changed.
    """
    adapter = getAdapter(context, IShortUrlAdapter, name="short-url-adapter")
    adapter.updateUrl()
    context.reindexObject()
